<?php 
require_once $_SERVER['DOCUMENT_ROOT'].'/inc/core/env.inc.php';

$return["success"] = false;
$return["html"] = null;
$return["jscript"] = null;
$return["error"] = null;

if ($_USER->asPermission('mod_user') || $_USER->get("id") == $_POST["id"]) {
	
	//fields controll
	$frmFields = new Fields();
	$frmFields->addFiels("name", "string", $_POST["name"]);
	$frmFields->addFiels("surname", "string", $_POST["surname"]);
	$frmFields->addFiels("email", "email", $_POST["email"]);
	$validFields = $frmFields->isValid();
	$duplicateEmail = User::exist($_POST["email"]);
	$action = null;

	if ($_POST["id"] == 0 && !$duplicateEmail && $validFields) {
		$action = 'input';
	}
	
	if ($_POST["id"] > 0) {
		if ($_POST["email"] == $_USER->get("email")) {
			$action = 'modify';
		}
	}
	
	//insert
	if ($action == 'input') {
		
		$res = $_USER::create($_POST["email"]);
			
		$sql = "UPDATE ".$_DB->getPrefix()."users SET name = '".$_POST["name"]."', surname = '".$_POST["surname"]."' WHERE id = '".$res["uId"]."'";
		$_DB->query($sql);
	
		//send email
		$body = file_get_contents($_SITE['path']['dir']['blocks']['containers']['email'].'/email-ins-user.tag.html');
		$body = str_replace($_TAGS["e-in-name-surname"], $_POST["name"].' '.$_POST["surname"], $body);
		$body = str_replace($_TAGS["e-in-u-nick"], $res["nick"], $body);
		$body = str_replace($_TAGS["e-in-u-pass"], $res["pass"], $body);
		
		$domainLevel2 = str_replace("www.", "", $_SITE["domain"]);
		$body = str_replace($_TAGS["e-domain"], $domainLevel2, $body);
			
		$mail = new Mail($_POST["email"], $res["nick"], 'no-reply@'.$domainLevel2, 'Dati account '.$domainLevel2, $body);
			
		if(!$mail->send()) {
			$log = new Log('User.php', 'setUser.php', 'email not send, new user: '.$res["nick"].' pass: '.$res["pass"]);
			$log->insert();
		}
			
		$return["success"] = true;
		$return["jscript"] = 'loadSetPermissions('.$res["uId"].')';
			
	}
	
	//modify
	if ($action == 'modify') {
		$sql = "UPDATE ".$_DB->getPrefix()."users SET name = '".$_POST["name"]."', surname = '".$_POST["surname"]."', email = '".$_POST["email"]."' WHERE id = '".$_POST["id"]."'";
		$_DB->query($sql);
	
		$return["success"] = true;
		$return["jscript"] = 'loadSetUser('.$_POST["id"].')';
	}	

	if ($duplicateEmail) {
		$return["error"] = 'Error duplicate email.';
	}
	
	if (!$frmFields->isValid()) {
		$return["error"] = 'Error fields not valid.';
	}
	
} else {
	$return["error"] = 'Error not have permission.';
}

echo '('.json_encode($return).')';

?>